﻿using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Niaofei.Domain.Shared;
using System.Globalization;
using System.Text.Json;

namespace Niaofei.Application
{
    public class NiaofeiAppService
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly IHttpContextAccessor _httpContextAccessor;

        public NiaofeiAppService(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
            _httpContextAccessor = serviceProvider.GetRequiredService<IHttpContextAccessor>();
        }

        public IMapper Mapper { get => _serviceProvider.GetRequiredService<IMapper>(); }

        public CurrentUser? CurrentUser { get => GetCurrentUser(); }

        private CurrentUser? GetCurrentUser()
        {
            if (_httpContextAccessor.HttpContext?.User.Claims == null ||
                _httpContextAccessor.HttpContext?.User.Claims.Count() == 0)
            {
                return null;
            }

            var claims = _httpContextAccessor.HttpContext!.User.Claims.ToList();

            var currentUser = new CurrentUser()
            {
                Id = claims.FirstOrDefault(m => m.Type == "Id")?.Value,
                Avatar = claims.FirstOrDefault(m => m.Type == "Avatar")?.Value,
                Email = claims.FirstOrDefault(m => m.Type == "Email")?.Value,
                Mobile = claims.FirstOrDefault(m => m.Type == "Mobile")?.Value,
                NickName = claims.FirstOrDefault(m => m.Type == "NickName")?.Value,
                UserName = claims.FirstOrDefault(m => m.Type == "UserName")?.Value,
                Roles = JsonSerializer.Deserialize<List<int>>(claims.FirstOrDefault(m => m.Type == "Role")?.Value ?? "[]"),
            };

            if (int.TryParse(claims.FirstOrDefault(m => m.Type == "Age")?.Value, NumberStyles.None, null, out var age))
            {
                currentUser.Age = age;
            }

            if (int.TryParse(claims.FirstOrDefault(m => m.Type == "DeptId")?.Value, NumberStyles.None, null, out var deptId))
            {
                currentUser.DeptId = deptId;
            }

            if (int.TryParse(claims.FirstOrDefault(m => m.Type == "Gender")?.Value, NumberStyles.None, null, out var gender))
            {
                currentUser.Gender = gender;
            }

            if (int.TryParse(claims.FirstOrDefault(m => m.Type == "Status")?.Value, NumberStyles.None, null, out var status))
            {
                currentUser.Status = status;
            }

            return currentUser;
        }
    }
}
